import { _decorator, BoxCollider2D, CircleCollider2D, Color, Component, director, ERigidBody2DType, instantiate, Node, PolygonCollider2D, RigidBody2D, Sprite, tween, UIOpacity, UITransform, Vec4, view } from 'cc';
import { HoleAction } from './HoleAction';
import { PinAction } from './PinAction';
import { ResourcePool } from './ResourcePool';
import { ColorDate } from './ColorDate';
import { Global } from './Global';
import { events } from './Enums';
const { ccclass, property } = _decorator;

@ccclass('ElementAction')
export class ElementAction extends Component {
    ele_color: ColorDate | null = null;

    start() {
        // 可初始化逻辑
    }

    update(deltaTime: number) {
        const posY = this.node.position.y;
        const visibleHeightHalf = view.getVisibleSize().height / 2;
        if (posY < -visibleHeightHalf) {
            this.node.removeFromParent();
            director.emit(events.remove_element, this);
        }
    }

    /** 统计当前节点下的HoleAction子节点数量 */
    public get_hole_num(): number {
        let count = 0;
        this.node.children.forEach(child => {
            if (child.getComponent(HoleAction)) count++;
        });
        return count;
    }

    /**
     * 初始化元素颜色及碰撞分组
     * @param group_id 组id
     * @param ele_color 颜色信息
     */
    public init_element(group_id: number, ele_color: ColorDate) {
        this.ele_color = ele_color;

        const rb = this.node.getComponent(RigidBody2D);
        if (rb) rb.group = group_id;

        this.node.getComponents(BoxCollider2D).forEach(collider => collider.group = group_id);
        this.node.getComponents(CircleCollider2D).forEach(collider => collider.group = group_id);
        this.node.getComponents(PolygonCollider2D).forEach(collider => collider.group = group_id);

        this.set_img_color(ele_color, 190);
    }

    /** 设置所有名为"img"子节点的Sprite颜色和透明度 */
    private set_img_color(color: ColorDate, alpha: number) {
        this.node.children.forEach(child => {
            if (child.name === "img") {
                const sprite = child.getComponent(Sprite);
                if (sprite) {
                    sprite.color = new Color(color.r, color.g, color.b, alpha);
                }
            }
        });
    }

    /**
     * 初始化钉子，自动在HoleAction位置实例化pin预制件并初始化
     * @param group_id 碰撞组id
     * @param color_pin_arr 钉子颜色数组，会被shift消耗
     */
    public init_pin(group_id: number, color_pin_arr: ColorDate[]) {
        this.node.children.forEach(child => {
            const hole = child.getComponent(HoleAction);
            if (hole && color_pin_arr.length > 0) {
                const pinPrefab = ResourcePool.instance.get_prefab("pin");
                const newPin = instantiate(pinPrefab);
                this.node.addChild(newPin);
                newPin.setPosition(child.position);
                const pinComp = newPin.getComponent(PinAction);
                if (pinComp) {
                    pinComp.init_date(group_id, color_pin_arr.shift()!, hole);
                }
            }
        });
    }

    /** 初始化所有HoleAction节点，隐藏环形效果 */
    public init_hole() {
        this.node.children.forEach(child => {
            const hole = child.getComponent(HoleAction);
            if (hole) hole.hide_holering();
        });
    }

    /** 获取所有子节点中PinAction组件且含pin_color的钉子，加入传入数组 */
    get_pin_color(arr: PinAction[]) {
        this.node.children.forEach(child => {
            const pin = child.getComponent(PinAction);
            if (pin && pin.pin_color) {
                arr.push(pin);
            }
        });
    }

    /**
     * 闪烁所有名为"img"子节点的UIOpacity组件，完成后恢复不透明
     * @param duration 每次动画时长，默认0.3秒
     */
    public flash_img(duration = 0.3) {
        this.node.children.forEach(child => {
            if (child.name === "img") {
                const opacityComp = child.getComponent(UIOpacity);
                if (opacityComp) {
                    opacityComp.opacity = 100;
                    tween(opacityComp)
                        .to(duration, { opacity: 200 }, Global.our_easing)
                        .to(duration, { opacity: 100 }, Global.our_easing)
                        .to(duration, { opacity: 200 }, Global.our_easing)
                        .to(duration, { opacity: 100 }, Global.our_easing)
                        .to(duration, { opacity: 255 }, Global.our_easing)
                        .call(() => { opacityComp.opacity = 255; })
                        .start();
                }
            }
        });
    }

    /**
     * 设置该层为黑色背景或恢复原色
     * @param is_bg true为黑色背景，false为恢复原色
     */
    public set_layer_bg_or_origin(is_bg: boolean) {
        const rb = this.node.getComponent(RigidBody2D);
        if (!rb) return;

        if (is_bg) {
            rb.type = ERigidBody2DType.Static;
            this.node.children.forEach(child => {
                child.active = false;
                if (child.name === "img") {
                    child.active = true;
                    this.set_img_color(ColorDate.new_bean(0, 0, 0, 0), 180);
                }
            });
        } else {
            this.node.children.forEach(child => { child.active = true; });
            if (this.ele_color) this.set_img_color(this.ele_color, 190);
            rb.type = ERigidBody2DType.Dynamic;
        }
    }
}
